#include "head.hpp"

string TRANSTOHEX(int x) // 转16进制
{
    char str[35]; // 32+2+1
    snprintf(str, sizeof(str), "0x%x", x);
    return str;
}

Init init;

int main()
{
    key_t key = ftok(PATH_NAME, ID);
    if (key == -1)
    {
        perror("ftok");
        exit(1);
    }
    log("ftok key success", Debug) << "key: " << TRANSTOHEX(key) << endl;
    // sleep(10);

    // 创建共享内存
    int shmid = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0664);
    if (shmid == -1)
    {
        perror("shmid");
        exit(2);
    }
    log("shmget success", Debug) << "shmid: " << shmid << endl;
    // sleep(10);

    // 挂接shm
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == (char *)-1)
    {
        perror("shmat");
        exit(3);
    }
    log("shmat success", Debug) << "shmaddr: " << (void *)shmaddr << endl;
    // sleep(10);

    // 进行读操作
    // 读，利用管道，构建访问控制
    int fifo_fd = Open(FIFO_NAME, READ);
    while(true)
    {
        Wait(fifo_fd);
        cout << shmaddr << endl;
        if (strcmp(shmaddr, "quit") == 0)
        {
            log("server quit", Notice) << endl;
            break;
        }
    }

    // while (true)
    // {
    //     cout << shmaddr << endl;
    //     if (strcmp(shmaddr, "quit") == 0)
    //     {
    //         log("server quit", Notice) << endl;
    //         break;
    //     }
    //     sleep(1);
    // }

    // 分离挂接
    int ret = shmdt(shmaddr);
    assert(ret != -1);
    log("shmdt success", Debug) << "shmaddr: " << (void *)shmaddr << endl;
    // sleep(10);

    // 删除共享内存
    int n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    log("shmrm success", Debug) << "shmid: " << shmid << endl;
    return 0;
}